package com.example.superjson;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;

import com.example.superjson.constant.Constants;
import com.example.superjson.util.HTTPUtil;
import com.example.superjson.util.JavaToJson;
import com.example.superjson.view.LinearInsView;

import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

public class ShowRTFluxFragment extends Fragment{
	private String title;
	private List<Map<String, String>> dataList;
	private Map<String,LinearInsView> linearInsViewMap = new HashMap<String,LinearInsView>();
	private LinearLayout layout_instruments1;
	private LinearLayout layout_instruments2;
	private static final String TAG = "ShowRTFluxFragment";
	private Handler netHandler = new Handler();
	private String url;
	private String service;
	private String type;
	private String catidrtflux;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_rtflux, container , false);
		layout_instruments1 = (LinearLayout) view.findViewById(R.id.layout_instruments1);
		layout_instruments2 = (LinearLayout) view.findViewById(R.id.layout_instruments2);
		Log.i(TAG,"ShowRTFluxFragmentinflated");
		service = "BoardService.smcavs";
		type = "getDataByDateTile";
		catidrtflux = "SSDLND";
		
		title = (String) getArguments().get("title");
		try {Log.i(TAG, (String) getArguments().get("data"));
			dataList = (List<Map<String, String>>) JavaToJson.transToJava((String) getArguments().get("data"), List.class);
			int i = 0;
			for (Map<String,String> datamap : dataList) {
				i++;
				String equipmentname = datamap.get("equipmentname");
				float rtvalue = Float.parseFloat(datamap.get("rtvalue"));
				LinearInsView linearInsView = new LinearInsView(getActivity());
				linearInsView.setInsname(equipmentname);
				linearInsView.setValue(rtvalue);
				linearInsViewMap.put(equipmentname, linearInsView);
				if(i<=3){
					layout_instruments1.addView(linearInsView);
				}else{
					layout_instruments2.addView(linearInsView);
				}
				
			}
		} catch (JsonParseException e) {
			Log.i(TAG, "JsonParseException", e);
		} catch (JsonMappingException e) {
			Log.i(TAG, "JsonMappingException", e);
		} catch (IOException e) {
			Log.i(TAG, "IOException", e);
		}
		netHandler.post(runnable);
		return view;
		
	}
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		// TODO Auto-generated method stub
		Log.i(TAG, "onDestroy removeCallbacks");
		netHandler.removeCallbacks(runnable);
	}


	Runnable runnable = new Runnable() {
		@Override
		public void run() {
			
			url = Constants.SmartMineWeb + service + "?type=" + type  + "&catid="+catidrtflux;
			Log.e(TAG+" RT url", url);
			new RtDownload().execute(url);
			netHandler.postDelayed(this, 2000);
		}
	};
	
	
	public void refresh(){
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		StringBuffer sb = new StringBuffer();
		sb.append(String.format("%d-%d",
				calendar.get(Calendar.HOUR_OF_DAY),
				calendar.get(Calendar.MINUTE)));
		try {
			dataList = (List<Map<String, String>>) JavaToJson.transToJava((String) getArguments().get("data"), List.class);
			for (Map<String,String> datamap : dataList) {
				String equipmentname = datamap.get("equipmentname");
				float rtvalue = Float.parseFloat(datamap.get("rtvalue"));
				LinearInsView linearInsView = linearInsViewMap.get(equipmentname);
				linearInsView.setInsname(equipmentname + "  "+sb);
				linearInsView.setValue(rtvalue);
			}
		} catch (JsonParseException e) {
			Log.i(TAG, "JsonParseException", e);
		} catch (JsonMappingException e) {
			Log.i(TAG, "JsonMappingException", e);
		} catch (IOException e) {
			Log.i(TAG, "IOException", e);
		}
	}
	
	public class RtDownload extends AsyncTask<String, Void, String>{
		@Override
		protected String doInBackground(String... params) {
			int count = params.length;
			String result = "";
			for (int i = 0; i < count; i++) {
				try {
					result += HTTPUtil.downloadUrl(params[i]);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				if (isCancelled())
					break;
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			Log.i(TAG+ " refreshing", result+"");
			try {
				Map<String, Object> resultMap = (Map<String, Object>) JavaToJson
						.transToJava(result, Map.class);
				String title3 = (String) resultMap.get("title");
				dataList = (List<Map<String, String>>) resultMap.get("data");
				refresh();
			} catch (JsonParseException e) {
				Log.i(TAG, "JsonParseException", e);
			} catch (JsonMappingException e) {
				Log.i(TAG, "JsonMappingException", e);
			} catch (IOException e) {
				Log.i(TAG, "IOException", e);
			}
		}
		
		
	}
	
}
